package com.gy.paidao.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.google.gson.reflect.TypeToken;
import com.gy.paidao.MyApplication;
import com.gy.paidao.R;
import com.gy.paidao.bean.BaseBean;
import com.gy.paidao.main.bean.ActivityBean;
import com.gy.paidao.main.view.MapDetailMarker;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.IMFileModel;
import com.gy.paidao.util.IMUploadSuccessListener;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.MarkerBitmapUpdataManager;
import com.gy.paidao.util.SPHelper;
import com.gy.paidao.util.Urls;
import com.gy.paidao.util.map.AMapUitls;
import com.jky.struct2.http.core.AjaxParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @author GY
 * @date 16/3/2
 * @Description:地图页
 */
public class MainMapFragment extends BaseFragment {

    private View mRoot;
    private ImageView imgLoc;
    private MapUtils aMapUitls;
    private MapView mapView;
    private LatLng lastCenter;//地图中心
    private String userLoginID;
    private List<ActivityBean> datas, requestList;
    private boolean isShow =false;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if("new_bubble".equals(intent.getAction())){
                datas.clear();
                dorequestActivity();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRoot == null) {
            mRoot = inflater.inflate(R.layout.fg_main_map, null);
            mapView = (MapView) mRoot.findViewById(R.id.fg_map);
            mapView.onCreate(savedInstanceState);
            init();
            initView();
            dorequestActivity();
        }
        ViewGroup parent = (ViewGroup) mRoot.getParent();
        if (parent != null) {
            parent.removeView(mRoot);
        }
        return mRoot;
    }

    @Override
    protected void init() {
        super.init();
        userLoginID = SPHelper.getInstance(getActivity()).getStringData("userLoginID", null);
        datas = new ArrayList<ActivityBean>();
        requestList = new ArrayList<ActivityBean>();
        IntentFilter filter = new IntentFilter();
        filter.addAction("new_bubble");
        mContext.registerReceiver(receiver,filter);
        Drawable marker = this.getResources().getDrawable(
                R.drawable.ic_map_marker_bg);
        aMapUitls = new MapUtils(getActivity(), mapView, marker);
        if (!TextUtils.isEmpty(MyApplication.CURRENT_Y) && !TextUtils.isEmpty(MyApplication.CURRENT_X)) {
            lastCenter = new LatLng(Double.valueOf(MyApplication.CURRENT_Y), Double.valueOf(MyApplication.CURRENT_X));
            aMapUitls.setZoom(AMapUitls.ZOOM_DETAIL);
            aMapUitls.setAndMoveCenter(Double.valueOf(MyApplication.CURRENT_Y), Double.valueOf(MyApplication.CURRENT_X));
        }
        MarkerBitmapUpdataManager.getInstance().addListener(markerBitmapUpdataListener);
    }

    @Override
    protected void initView() {
        super.initView();
        imgLoc = (ImageView) mRoot.findViewById(R.id.map_loc);
        imgLoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aMapUitls.startLocation();
            }
        });
    }

    class MapUtils extends AMapUitls {

        public MapUtils(Context context, MapView mMapView, Drawable marker) {
            super(context, mMapView, marker);
        }


        @Override
        protected View setWindowData(Marker marker) {
            int loc = Integer.valueOf(marker.getTitle());
            return null;
        }

        @Override
        protected void mapInWindorClick(Marker marker) {
        }

        @Override
        public void onMapClick(LatLng latLng) {
            super.onMapClick(latLng);
            LogUtil.e("onMapClick");
        }

        @Override
        protected void mapMarkerClick(Marker marker) {
            LogUtil.e("mapMarkerClick:"+marker.getTitle());
            int loc = Integer.valueOf(marker.getTitle());
            Intent intent = new Intent(mContext, BabbleDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("activity", requestList.get(loc));
            intent.putExtras(bundle);
            mContext.startActivity(intent);
            AnimUtil.pushLeftInAndOut(getActivity());
        }

        @Override
        protected void mapMoveFinishCallBack(LatLng center, float distance) {
            LogUtil.e("mapMoveFinishCallBack");
        }

        /**
         * 定位成功
         */
        @Override
        public void onAmapLocationListener(AMapLocation aMapLocation) {
            datas.clear();
            aMapUitls.setAndMoveCenter(aMapLocation.getLatitude(),aMapLocation.getLongitude());
            showLoadDialog();
            dorequestActivity();
        }

        @Override
        public void onAmapLocationFail() {
            showToast("定位失败，请稍后重试");
        }

        @Override
        public void mapZoomChange(LatLng center, int flag) {
            super.mapZoomChange(center, flag);
            LogUtil.e("mapZoomChange");

        }
    }

    /**
     * 请求列表
     */
    private void dorequestActivity() {
        params = new AjaxParams();
        params.put("latitude", MyApplication.CURRENT_Y+"");
        params.put("longitude",MyApplication.CURRENT_X+"");
//        params.put("latitude", "39.963053");
//        params.put("longitude", "116.477316");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.get(Urls.url_map_list, params, callBack, 0);
    }

    @Override
    protected void handlerBean(int requestCode, BaseBean baseBean) {
        super.handlerBean(requestCode, baseBean);
        if (baseBean.success) {
            String data = String.valueOf(baseBean.data);
            switch (requestCode) {
                case 0://请求列表
                    if (!TextUtils.isEmpty(data)) {
                        if (!TextUtils.isEmpty(data) && !"[]".equals(data)) {
                            Type type = new TypeToken<List<ActivityBean>>() {
                            }.getType();
                            requestList = gson.fromJson(data, type);

                            for (ActivityBean bean : requestList) {
                                bean.setX(bean.longitude + "");
                                bean.setY(bean.latitude + "");
                            }
                            aMapUitls.setMapBaseDrawable(new MapDetailMarker(getActivity()));
//                            aMapUitls.setMoveSelf(true);
                            aMapUitls.setListData(requestList);
                            for (int i = 0; i < requestList.size(); i++) {
                                final int finalI = i;
                                if ("image".equals(requestList.get(i).mediaType)) {
                                    IMFileModel.getInstance(getActivity()).downFile(requestList.get(i).mediaPaths, new IMUploadSuccessListener() {
                                        @Override
                                        public void messageUploadFileSuccess(String url) {
                                            LogUtil.e("加载成功------" + finalI+"  "+url);
                                            requestList.get(finalI).localPath = url;
                                            isShow = true;
                                            handler.sendEmptyMessage(0);
                                        }

                                        @Override
                                        public void messageUploadFail(String path) {
                                            LogUtil.e("加载失败-----");
                                            requestList.get(finalI).localPath = "";
                                            isShow = true;
                                            handler.sendEmptyMessage(0);
                                        }
                                    }, "png", requestList.get(i).id + "");
                                } else if ("video".equals(requestList.get(i).mediaType)) {
                                    IMFileModel.getInstance(getActivity()).downFile(requestList.get(i).thumbnailUrl, new IMUploadSuccessListener() {
                                        @Override
                                        public void messageUploadFileSuccess(String url) {
                                            LogUtil.e("加载成功------" + finalI+"  "+url);
                                            requestList.get(finalI).localPath = url;
                                            isShow = true;
                                            handler.sendEmptyMessage(0);
                                        }

                                        @Override
                                        public void messageUploadFail(String path) {
                                            LogUtil.e("加载失败-----");
                                            requestList.get(finalI).localPath = "";
                                            isShow = true;
                                            handler.sendEmptyMessage(0);
                                        }
                                    }, "png", requestList.get(i).id + "");
                                }
                            }

                        }
                    }
                    break;
            }
        } else {
            if (!TextUtils.isEmpty(baseBean.errMsg)) {
                showToast(baseBean.errMsg);
            }
        }
    }

    MarkerBitmapUpdataManager.MarkerBitmapUpdataListener markerBitmapUpdataListener = new MarkerBitmapUpdataManager.MarkerBitmapUpdataListener() {
        @Override
        public void markerUpdate(int id) {
            if (requestList.size() > 0) {
                ActivityBean bean = requestList.get(requestList.size() - 1);
                if (bean.id == id) {
                    aMapUitls.setListData(requestList);
                }
            }
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(isShow){
                isShow = false;
            } else {
                return;
            }
            int i = 0;
            for (ActivityBean bean : requestList) {
                if (!TextUtils.isEmpty(bean.localPath)) {
                    i++;
                } else {
                    if ("image".equals(requestList.get(i).mediaType)) {
                        if(TextUtils.isEmpty(requestList.get(i).mediaPaths)){
                            i++;
                        }
                    } else {
                        if(TextUtils.isEmpty(requestList.get(i).thumbnailUrl)){
                            i++;
                        }
                    }
                }
            }

            if (i == requestList.size()) {
                LogUtil.e("---------------------");
                aMapUitls.setListData(requestList);
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}
